<template>
  <div class="order-list">
    <div class="page-header">
      <h2>订单列表</h2>
      <el-button type="primary" @click="$router.push('/orders/add')">创建订单</el-button>
    </div>
    
    <div class="search-bar">
      <el-select v-model="searchStatus" placeholder="订单状态" clearable>
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" @click="searchOrders">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="orders"
      border
      style="width: 100%">
      <el-table-column
        prop="orderId"
        label="订单ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="customerId"
        label="客户ID"
        width="160">
      </el-table-column>
      <el-table-column
        prop="orderDate"
        label="下单时间"
        width="280">
        <template slot-scope="scope">
          {{ formatDate(scope.row.orderDate) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="totalAmount"
        label="订单金额"
        width="240">
        <template slot-scope="scope">
          {{ scope.row.totalAmount }} 元
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="订单状态"
        width="240">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="viewDetail(scope.row)">查看详情</el-button>
          <el-button
            size="mini"
            type="success"
            @click="createDelivery(scope.row)"
            v-if="scope.row.status === 'paid'">创建配送</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination">
    </el-pagination>
    
    <!-- 创建配送信息对话框 -->
    <el-dialog title="创建配送信息" :visible.sync="deliveryDialogVisible" width="500px">
      <el-form :model="deliveryForm" :rules="deliveryRules" ref="deliveryForm" label-width="100px">
        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input type="textarea" v-model="deliveryForm.shippingAddress" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="配送公司" prop="carrier">
          <el-input v-model="deliveryForm.carrier"></el-input>
        </el-form-item>
        <el-form-item label="预计送达" prop="estimatedDelivery">
          <el-date-picker
            v-model="deliveryForm.estimatedDelivery"
            type="date"
            placeholder="选择预计送达日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deliveryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDelivery">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import orderApi from '@/api/order'
import deliveryApi from '@/api/delivery'
import moment from 'moment'

export default {
  name: 'OrderList',
  
  data() {
    return {
      loading: true,
      orders: [],
      allOrders: [],
      searchStatus: '',
      statusOptions: [
        { value: 'pending', label: '待处理' },
        { value: 'paid', label: '已支付' },
        { value: 'shipped', label: '已发货' },
        { value: 'delivered', label: '已送达' },
        { value: 'cancelled', label: '已取消' }
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      deliveryDialogVisible: false,
      deliveryForm: {
        orderId: null,
        shippingAddress: '',
        carrier: '',
        estimatedDelivery: null
      },
      deliveryRules: {
        shippingAddress: [
          { required: true, message: '请输入收货地址', trigger: 'blur' }
        ],
        carrier: [
          { required: true, message: '请输入配送公司', trigger: 'blur' }
        ]
      }
    }
  },
  
  created() {
    this.fetchOrders()
  },
  
  methods: {
    // 获取订单列表
    async fetchOrders() {
      this.loading = true
      try {
        const response = await orderApi.getAllOrders()
        this.allOrders = response.data
        this.filterOrders()
        this.loading = false
      } catch (error) {
        this.$message.error('获取订单列表失败')
        this.loading = false
      }
    },
    
    // 过滤订单
    filterOrders() {
      let filtered = [...this.allOrders]
      
      // 按状态过滤
      if (this.searchStatus) {
        filtered = filtered.filter(item => item.status === this.searchStatus)
      }
      
      this.total = filtered.length
      
      // 分页
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.orders = filtered.slice(start, end)
    },
    
    // 搜索订单
    searchOrders() {
      this.currentPage = 1
      this.filterOrders()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchStatus = ''
      this.currentPage = 1
      this.filterOrders()
    },
    
    // 查看订单详情
    viewDetail(row) {
      this.$router.push(`/orders/${row.orderId}`)
    },
    
    // 创建配送
    createDelivery(row) {
      this.deliveryForm.orderId = row.orderId
      this.deliveryForm.shippingAddress = ''
      this.deliveryForm.carrier = ''
      this.deliveryForm.estimatedDelivery = null
      this.deliveryDialogVisible = true
    },
    
    // 提交配送信息
    submitDelivery() {
      this.$refs.deliveryForm.validate(async (valid) => {
        if (valid) {
          try {
            const delivery = {
              ...this.deliveryForm,
              status: 'processing'
            }
            
            const response = await deliveryApi.addDelivery(delivery)
            if (response.data.success) {
              this.$message.success(response.data.message)
              this.deliveryDialogVisible = false
              this.fetchOrders()
            } else {
              this.$message.error(response.data.message)
            }
          } catch (error) {
            this.$message.error('创建配送信息失败')
          }
        } else {
          return false
        }
      })
    },
    
    // 删除订单
    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await orderApi.deleteOrder(row.orderId)
        if (response.data.success) {
          this.$message.success(response.data.message)
          if (this.orders.length === 1) {
            this.currentPage--
          }
          this.fetchOrders()
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除订单失败')
        }
      }
    },
    
    // 格式化日期
    formatDate(date) {
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    
    // 获取状态类型
    getStatusType(status) {
      const map = {
        'pending': 'info',
        'paid': 'success',
        'shipped': 'primary',
        'delivered': 'success',
        'cancelled': 'danger'
      }
      return map[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        'pending': '待处理',
        'paid': '已支付',
        'shipped': '已发货',
        'delivered': '已送达',
        'cancelled': '已取消'
      }
      return map[status] || status
    },
    
    // 页面大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.filterOrders()
    },
    
    // 页码变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.filterOrders()
    }
  }
}
</script>

<style scoped>
.order-list {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 